//
//  GoodDetailViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/9.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "GoodDetailViewController.h"
#import "PurchaseViewController.h"
#import "YXCustomActionSheet.h"
#import "DyShare.h"

@interface GoodDetailViewController () <UIWebViewDelegate, YXCustomActionSheetDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIView *bottombar;
@property (strong, nonatomic) UIButton *buttonCol;
@property (assign, nonatomic) BOOL iscol;

@property (strong, nonatomic) NSString *url;
@property (strong, nonatomic) UIImage *shareImg;

@end

@implementation GoodDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBack:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonShare.frame = CGRectMake(0, 0, 26, 20);
    [buttonShare setBackgroundImage:[UIImage imageNamed:@"goodshare"] forState:UIControlStateNormal];
    UIBarButtonItem *btnShare = [[UIBarButtonItem alloc]initWithCustomView:buttonShare];
    [buttonShare addTarget:self action:@selector(clickShare:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnShare;
    
    [self makeBottomBar];
    [self getDetail];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationWhite:self];
    
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:self.gooddata.goods_name WithTextColor:[UIColor blackColor]];
    self.url = [NSString stringWithFormat:@"https://app.zallhy.com/h5/mobile/#/product_detail/%@/%@", self.gooddata.goods_id, [UserData usertoken]];
    self.webView.delegate = self;
    [self.webView setUserInteractionEnabled:YES];//是否支持交互
    [self.webView setScalesPageToFit:YES];//自动缩放以适应屏幕
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    
    [self downloadShareImage];
}

- (void)makeBottomBar {
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    line.backgroundColor = LineColor;
    [self.bottombar addSubview:line];
    
    self.buttonCol = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonCol.frame = CGRectMake(ScreenW / 8, 13, 25, 25);
    //[buttonCol setBackgroundImage:[UIImage imageNamed:@"goodcol"] forState:UIControlStateNormal];
    [self.buttonCol setBackgroundImage:[UIImage imageNamed:@"取消收藏"] forState:UIControlStateNormal];
    [self.buttonCol addTarget:self action:@selector(clickColButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottombar addSubview:self.buttonCol];
    
    UIButton *buttonQ = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonQ.frame = CGRectMake(ScreenW * 3 / 8, 13, 25, 25);
    [buttonQ setBackgroundImage:[UIImage imageNamed:@"goodquery"] forState:UIControlStateNormal];
    [self.bottombar addSubview:buttonQ];
    [buttonQ addTarget:self action:@selector(clickQuery:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(ScreenWidth / 2 + 30, 10, ScreenWidth / 2 - 60, 30);
    [button setTitle:@"购买" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor blackColor];
    [self.bottombar addSubview:button];
    [button addTarget:self action:@selector(clickPurchase:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 2.f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)goPop {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getDetail {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [[NSString stringWithFormat:@"%@/product/productDetail?productId=%@", APIYIGOU, self.gooddata.goods_id]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *product = [[dict objectForKey:@"data"] objectForKey:@"product"];
        NSString *count_user = [product objectForKey:@"count_user"];
        if (![count_user isEqualToString:@""] && [count_user integerValue] > 0) {
            self.iscol = YES;
            [self.buttonCol setBackgroundImage:[UIImage imageNamed:@"收藏"] forState:UIControlStateNormal];
        } else {
            self.iscol = NO;
            [self.buttonCol setBackgroundImage:[UIImage imageNamed:@"取消收藏"] forState:UIControlStateNormal];
        }
    } error:^(YTKBaseRequest *request) {
    } failure:^(YTKBaseRequest *request) {
        //[ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)clickColButton:(UIButton *)button {
    if (self.iscol) {
        [self clickCancelCol];
    } else {
        [self clickCol];
    }
}

- (void)clickCol {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [[NSString stringWithFormat:@"%@/userCenter/ScProduct?goods_id=%@", APIYIGOU, self.gooddata.goods_id]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        self.iscol = YES;
        [self.buttonCol setBackgroundImage:[UIImage imageNamed:@"收藏"] forState:UIControlStateNormal];
        [ViewFactory showSuccess:[dict objectForKey:@"message"]];
    } error:^(YTKBaseRequest *request) {
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)clickCancelCol {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [[NSString stringWithFormat:@"%@/hyContent/delCollect?becollect_id=%ld", APIYIGOU, [self.gooddata.goods_id integerValue]]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        self.iscol = NO;
        [self.buttonCol setBackgroundImage:[UIImage imageNamed:@"取消收藏"] forState:UIControlStateNormal];
        [ViewFactory showSuccess:[dict objectForKey:@"message"]];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)clickQuery:(UIButton *)button {
    EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:self.gooddata.user_id conversationType:EMConversationTypeChat];
    [self.navigationController pushViewController:chatController animated:YES];
}

- (void)clickPurchase:(UIButton *)button {
    PurchaseViewController *vc = [[PurchaseViewController alloc] initWithNibName:@"PurchaseViewController" bundle:nil];
    vc.productId = self.gooddata.goods_id;
    vc.gooddata = self.gooddata;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)clickReport {
    DYBaseRequest *request = [DYBaseRequest new];
    //NSString *status = @"01";
    //report_obj举报对象，00：话题，01：文章，03：直播，04：商品
    //report_type举报类型,00：色情，01：反动，02：虚假，99：其他
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/addReport?report_obj=%@&report_obj_id=%@&report_type=%@&report_content=%@", APIYIGOU, @"04", self.gooddata.goods_id, @"00", @""];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"举报成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"举报失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)downloadShareImage {
    NSString *imgurl = @"";
    imgurl = self.gooddata.goods_pic_url;
    NSArray *array = [self.gooddata.goods_pic_url componentsSeparatedByString:@","];
    if (array.count > 0) {
        imgurl = array[0];
    }
    if (!self.shareImg) {
        [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:imgurl] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            self.shareImg = image;
        }];
    }
}

- (void)clickShare:(UIButton *)button {
    YXCustomActionSheet *cusSheet = [[YXCustomActionSheet alloc] init];
    cusSheet.delegate = self;
    NSArray *contentArray = @[@{@"name":@"朋友圈",@"icon":@"sns_pyq"},
                              @{@"name":@"微信",@"icon":@"sns_wx"},
                              @{@"name":@"新浪微博",@"icon":@"sns_wb"},
                              @{@"name":@"QQ ",@"icon":@"sns_qq"},
                              @{@"name":@"QQ空间 ",@"icon":@"sns_qzone"},
                              @{@"name":@"举报 ",@"icon":@"sns_jb"}];
    
    [cusSheet showInView:[UIApplication sharedApplication].keyWindow contentArray:contentArray];
}

- (void)customActionSheetButtonClick:(YXActionSheetButton *)btn {
    NSLog(@"第%li个按钮被点击了",(long)btn.tag);
    NSInteger index = btn.tag;

    DyShareType type;
    switch (index) {
        case 0:
            type = DyShareTypePengYouQuan;
            break;
        case 4:
            type = DyShareTypeQZone;
            break;
        case 2:
            type = DyShareTypeWeiBo;
            break;
        case 1:
            type = DyShareTypeWeiXin;
            break;
        case 3:
            type = DyShareTypeQQ;
            break;
        case 5: {
            [self clickReport];
            return;
        }
        default:
            break;
    }
    [[DyShare getInstance]shareWithShareType:type Content:@"" title:self.gooddata.goods_name url:self.url image:self.shareImg delegate:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    
    //OC调用JS是基于协议拦截实现的 下面是相关操作
    NSString *absolutePath = request.URL.absoluteString;
    
    NSString *scheme = @"rrcc://";
    
    if ([absolutePath hasPrefix:scheme]) {
        NSString *subPath = [absolutePath substringFromIndex:scheme.length];
        
        if ([subPath containsString:@"?"]) {//1个或多个参数
            
            if ([subPath containsString:@"&"]) {//多个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                NSArray *params = [parameter componentsSeparatedByString:@"&"];
                
                if (params.count == 2) {
                    if ([self respondsToSelector:sel]) {
                        [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
                    }
                }
                
                
            } else {//1个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                
                if ([self respondsToSelector:sel]) {
                    [self performSelector:sel withObject:parameter];
                }
                
            }
            
        } else {//没有参数
            NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            SEL sel = NSSelectorFromString(methodName);
            
            if ([self respondsToSelector:sel]) {
                [self performSelector:sel];
            }
        }
    }
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [ViewFactory showLoadingEnableTouch];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
//    NSString *script = [NSString stringWithFormat:
//                        @"var script = document.createElement('script');"
//                        "script.type = 'text/javascript';"
//                        "script.text = \"function ResizeImages() { "
//                        "var img;"
//                        "var maxwidth=%f;"
//                        "for(i=0;i <document.images.length;i++){"
//                        "img = document.images[i];"
//                        "if(img.width > maxwidth){"
//                        "img.width = maxwidth;"
//                        "}"
//                        "}"
//                        "}\";"
//                        "document.getElementsByTagName('head')[0].appendChild(script);", ScreenWidth - 20];
//    [webView stringByEvaluatingJavaScriptFromString: script];
//    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    [ViewFactory dismissLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if (error) {
        NSDictionary *userinfo = error.userInfo;
        if (userinfo) {
            NSString *url = [userinfo objectForKey:@"NSErrorFailingURLStringKey"];
            if([url hasPrefix:@"rrcc://"]) {
                return;
            }
        }
    }
    [ViewFactory showErrorStrMsg:@"加载失败！"];
}

@end
